package content;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class InputXml {
	private String url = "c:/PageXmlDefault.xml";
	private String str = "<" + "?xml" + " " + "version=\"1.0\" " + "encoding="
			+ "\"UTF-8\"?>" + "\n" + "<pageview_list>" + "\n";
	private Element RootList;
	private List list;
	private String fileName;
	private int num;
	private FileWriter writer;
	
	public InputXml(String fileName) {
		this.fileName = fileName;
		add();
	}

	public List returnXMLList(String xmlUrl) throws Exception {
		SAXBuilder oBuilder = new SAXBuilder();
		Document oDoc = oBuilder.build(new File(xmlUrl));

		Element xmlRoot = oDoc.getRootElement(); // root element
		List RootList = xmlRoot.getChildren();

		return RootList;
	}

	public void add() {
		try {
			ReaderXml xml = new ReaderXml();
			String filePath = "c:/PageXmlDefault.xml";
			File file = new File(filePath);
			list = this.returnXMLList(url);
			
			for (int i = 0, j = 1; i < list.size(); j++, i++) {
				RootList = (Element) list.get(i);
				
				num = Integer.parseInt(RootList.getAttributeValue("linkpageindex"))+1;
					
				str += "<" + RootList.getName() + " " + "index= \""
						+ RootList.getAttributeValue("index") + "\"" + " "
						+ "linkpageindex=\""
						+ RootList.getAttributeValue("linkpageindex") + "\""
						+ " " + "pagename=\""
						+ RootList.getAttributeValue("pagename") + "\"" + " />"
						+ "\n";
			
			}

			str += "<" + RootList.getName() + " " + "index= \""
					+ RootList.getAttributeValue("index") + "\"" + " "
					+ "linkpageindex=\"";

			str += num;
			
			str += "\"" + " " + "pagename=\"" + fileName + "\"" + " />" + "\n";

			str += "</pageview_list>";
			
			outXml(filePath);
			
		} catch (Exception e) {

		}
	}

	public void outXml(String filePath) {
		try {
			writer = new FileWriter(filePath);
			writer.write(str);
		} catch (IOException e) {
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
			}
		}
	}
}
